﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FTBS.Models.BLO;
using FTBS.Models.DAO;
using FTBS.Models.Entities;
using FTBS.Models.Entities.Concert;
using PagedList;

namespace FTBS.Controllers
{
    public class TicketController : Controller
    {
        private ChairBLO _chairBlo = new ChairBLO();
        private RoomBLO _roomBlo = new RoomBLO();
        private ScheduleBLO _scheduleBlo = new ScheduleBLO();
        private TicketBLO _ticketBlo = new TicketBLO();
        private PriceTicketBLO _priceTicketBlo = new PriceTicketBLO();
        private ScheduleConcertEntityBLO _scheduleConcertEntityBlo = new ScheduleConcertEntityBLO();
        private TicketCartBLO _ticketCartBlo = new TicketCartBLO();

        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending, string fromDate, string toDate)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            List<ScheduleConcertEntity> listScheduleToShow = new List<ScheduleConcertEntity>();
            List<ScheduleConcertEntity> listSchedule = new List<ScheduleConcertEntity>();
            listSchedule = _scheduleConcertEntityBlo.LoadSchedules();

            //Variable for 2 datetime Picker
            var fromDateValue = DateTime.Today;
            var toDateValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));
            ViewBag.ToDate = toDateValue;
            ViewBag.FromDate = fromDateValue;

            if (fromDate == null && toDate == null)
            {
                foreach (var schedule in listSchedule)
                {
                    if (schedule.Date >= fromDateValue && schedule.Date <= toDateValue)
                    {
                        listScheduleToShow.Add(schedule);
                    }
                }
            }
            else
            {
                // Specify exactly how to interpret the string.
                IFormatProvider culture = new System.Globalization.CultureInfo("vi-VN", true);

                foreach (var schedule in listSchedule)
                {
                    //var showTimeOfSchedule = _showtimeBLO.GetShowTimeById(schedule.ShowTimeId);
                    if (schedule.Date >= DateTime.Parse(fromDate, culture, System.Globalization.DateTimeStyles.AssumeLocal)
                        && schedule.Date <= DateTime.Parse(toDate, culture, System.Globalization.DateTimeStyles.AssumeLocal))
                    {
                        listScheduleToShow.Add(schedule);
                    }
                }
                ViewBag.ToDate = DateTime.Parse(toDate, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                ViewBag.FromDate = DateTime.Parse(fromDate, culture, System.Globalization.DateTimeStyles.AssumeLocal);
            }


            ViewBag.NameSortParm = "film_name_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }
            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {

                listScheduleToShow = listScheduleToShow.Where(schedule => schedule.FilmName.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.TheaterName.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.RoomName.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.TimeForShow.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.Date.ToShortDateString().ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "film_name_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.FilmName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.FilmName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "theater_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.TheaterName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.TheaterName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "room_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.RoomName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.RoomName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "time_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.TimeForShow).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.TimeForShow).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "day_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.Date).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.Date).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.ScheduleId).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(listScheduleToShow.ToPagedList(pageNumber, pageSize));
        }

        /// <summary>
        /// create tickets with pure price of each theater in the first time when choose schedule
        /// </summary>
        /// <param name="scheduleId"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult CreateTickets(int scheduleId)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            ViewBag.ScheduleId = scheduleId;

            Schedule schedule = _scheduleBlo.GetScheduleById(scheduleId);
            int roomId = schedule.RoomId;
            ViewBag.RoomHeight = _roomBlo.GetRoomById(roomId).MaxHeight;
            //int theaterId = schedule.TheaterId;
            List<Chair> listChairs = _chairBlo.LoadChairsWithIsdeletedEqualFalse(roomId);
            List<Ticket> listOfTickets = new List<Ticket>();
            if (listChairs != null)
            {
                for (int i = 0; i < listChairs.LongCount(); i++)
                {
                    if (!_ticketBlo.CheckTicketToCreate(scheduleId, listChairs[i].ChairId))
                    {
                        Ticket ticket = new Ticket();
                        ticket.ChairId = listChairs[i].ChairId;
                        ticket.ScheduleId = scheduleId;
                        listOfTickets.Add(ticket);
                    }
                }
                if (listOfTickets.LongCount() != 0)
                {
                    _ticketBlo.CreateTickets(listOfTickets);
                }
            }
            return View(_chairBlo.LoadChairs(roomId));
        }

        /// <summary>
        /// submit creating tickets to save choosen ticketd
        /// </summary>
        /// <param name="listId"></param>
        /// <param name="scheduleId"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public String SubmitCreatingTickets(string listId, int scheduleId)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return "SessionTimeOut";
            }
            Schedule schedule = new Schedule();
            schedule = _scheduleBlo.GetScheduleById(scheduleId);
            int theaterId = schedule.TheaterId;
            int roomId = schedule.RoomId;
            List<Chair> listChairs = _chairBlo.LoadChairsWithIsdeletedEqualFalse(roomId);

            string[] strListChairId = listId.Split(' ');

            List<Ticket> listNotBookTickets = new List<Ticket>();
            List<Ticket> listSelectedTickets = new List<Ticket>();
            if (listChairs != null)
            {
                for (int i = 0; i < listChairs.LongCount(); i++)
                {
                    Ticket ticket = _ticketBlo.GetTicket(scheduleId, listChairs[i].ChairId);
                        if (!ticket.Status)
                        {
                            listNotBookTickets.Add(ticket);
                        }
                }
                if (!strListChairId[0].Equals(""))
                {
                    for (int j = 0; j < strListChairId.Length; j++)
                    {
                        Ticket ticket = _ticketBlo.GetTicket(scheduleId, Int32.Parse(strListChairId[j]));
                        listSelectedTickets.Add(ticket);
                    }
                }
                if (listNotBookTickets.LongCount() != 0)
                {
                    if (_ticketBlo.UpdateSelectdTickets(listNotBookTickets, listSelectedTickets, theaterId))
                    {
                        _scheduleBlo.UpdateCreatedTicket(schedule);
                        return "CreateSuccessfull";
                    }
                }
            }
            return "fail";
        }

        /// <summary>
        /// Redirect to View CheckOrderCode
        /// </summary>
        /// <returns></returns>
        public ViewResult CheckOrderCode()
        {
            ViewBag.TicketCart = new TicketCartConcertEntity();
            return View();
        }

        /// <summary>
        /// Check OrderCode
        /// </summary>
        /// <returns></returns>
        public PartialViewResult CheckOrderCodeResult(string cardId)
        {
            TicketCartConcertEntity ticketCartConcertEntity = new TicketCartConcertEntity();
            ticketCartConcertEntity = _ticketCartBlo.GetTicketCardIdByCartId(cardId);
            return PartialView(ticketCartConcertEntity);
        }

        public string CheckPriceTicketToCreateTicket(int scheduleId)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return "SessionTimeOut";
            }
            if (!_ticketBlo.CheckPriceToCreateTicket(scheduleId))
            {
                return "price less zero";
            }
            if (!_ticketBlo.CheckEnoughPriceTicketToCreateTicket(scheduleId))
            {
                return "not enough chairtype";
            }
            if (_ticketBlo.CheckPriceToCreateTicket(scheduleId) &&
                _ticketBlo.CheckEnoughPriceTicketToCreateTicket(scheduleId))
            {
                return "can create ticket";
            }
            return "fail";
        }
    }
}
